from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.chrome.service import Service
from webdriver_manager.chrome import ChromeDriverManager
import time
import re
import json

# 配置Chrome选项
options = webdriver.ChromeOptions()
# 启用性能日志，用于捕获网络请求
options.set_capability('goog:loggingPrefs', {'performance': 'ALL'})

# 初始化WebDriver
driver = webdriver.Chrome(
    service=Service(ChromeDriverManager().install()),
    options=options
)

# 存储省份与城市的对应关系（省份: [城市列表]）
province_cities = {}
# 存储城市码的字典
city_codes = {}

try:
    driver.get('http://app.wewe7788.cn/app/flash')
    time.sleep(2)  # 等待页面加载

    # 执行页面操作
    driver.find_element(By.XPATH, '//*[@id="block-left-menu"]/div[2]').click()
    time.sleep(1)
    driver.find_element(By.XPATH, '//*[@id="area-1-all-4001"]').click()
    time.sleep(1)
    driver.find_element(By.XPATH, '//*[@id="repeat-1-aaaa"]').click()
    time.sleep(1)
    driver.find_element(By.XPATH, '//*[@id="city-1-1101"]').click()
    time.sleep(1)
    
    # 点击下拉菜单
    province_menu = driver.find_element(By.XPATH, '/html/body/div[1]/div[2]/div[2]/div[2]/div[1]/div[1]/div[2]/select')
    # 遍历菜单
    for option in province_menu.find_elements(By.TAG_NAME, 'option'):
        province_name = option.text
        province_code = option.get_attribute('value')
        city_codes[province_name] = province_code
        print(f"# {province_name}")

        # 初始化该省份的城市列表
        province_cities[province_name] = []
        # 选中省份
        option.click()
        # 城市列表div
        city_list = driver.find_element(By.XPATH, '/html/body/div[1]/div[2]/div[2]/div[2]/div[1]/div[1]/div[3]')
        time.sleep(1)
        city_divs = city_list.find_elements(By.TAG_NAME, 'div')


        # 遍历city_list这个div内部的所有div，div里面有lable
        for city_div in city_divs:
            city_name = city_div.find_element(By.TAG_NAME, 'label').text
            city_code = city_div.find_element(By.TAG_NAME, 'input').get_attribute('value')
            #print(f"{city_name} 的城市码为：{city_code}")
            # 存储城市码
            # 去掉城市码是‘on’的城市
            if city_code != 'on':
                city_codes[city_name] = city_code
                province_cities[province_name].append(city_name)  # 将城市添加到对应省份
                print(f'"{city_name}":{city_code},')
        print(f" ")


    # 用city_codes以 "杭州市": "3301", 的形式打印出来，便于我用来硬编码代码
    # for city_name, city_code in city_codes.items():
    #     print(f'"{city_name}":{city_code}')

    # 按格式输出省份-城市列表
    print("\n省份与城市对应关系：")
    for province, cities in province_cities.items():
        if cities:  # 只输出有城市的省份
            # 拼接城市列表字符串，格式：["福州市", "厦门市", ...]
            cities_str = ', '.join([f'"{city}"' for city in cities])
            print(f'"{province}": [{cities_str}],')

    # 点击开始生成按钮
    start_button = driver.find_element(By.XPATH,
                                       '/html/body/div[1]/div[2]/div[2]/div[2]/div[2]/div[2]/div[1]/div[1]/button')
    start_button.click()

    # 等待请求完成
    time.sleep(3)  # 增加等待时间确保请求完成

    # 获取性能日志
    logs = driver.get_log('performance')

    # 查找包含请求参数的日志条目
    found_request = False
    for log in logs:
        try:
            message = json.loads(log['message'])
            message = message.get('message', {})

            if message.get('method') == 'Network.requestWillBeSent':
                request_data = message.get('params', {})
                request = request_data.get('request', {})

                if request.get('method') == 'POST' and 'app.wewe7788.cn' in request.get('url', ''):
                    found_request = True
                    print("\n捕获到POST请求:")
                    print(f"URL: {request.get('url')}")

                    # 提取POST数据
                    post_data = request.get('postData')
                    if post_data:
                        print("请求参数:")
                        print(post_data)

                    # 提取请求头
                    headers = request.get('headers', {})
                    print("\n请求头:")
                    for key, value in headers.items():
                        print(f"{key}: {value}")

        except Exception as e:
            continue

    if not found_request:
        print("\n未找到符合条件的POST请求。请检查：")
        print("1. 确保页面操作成功执行")
        print("2. 尝试增加等待时间")
        print("3. 检查请求URL是否包含 'app.wewe7788.cn'")

except Exception as e:
    print(f"发生错误: {str(e)}")

finally:
    input("\n按Enter键关闭浏览器...")
    driver.quit()